﻿using RAP.Framework.Libary.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using static RAP.Framework.Libary.DataSource.ServiceUtils;

namespace RAP.Framework.Libary.DataSource
{
  public static class Extensions
  {
    /// <summary>
    /// 检测数据查询结果是否包含错误
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static bool HasError(this object obj, bool defaultVal = false)
    {
      if (obj == null)
      {
        return defaultVal;
      }
      if (obj is string)
      {
        obj = obj.ToString().ToDictionary();
      }
      else if (obj is IDictionary)
      {
        var result = obj as IDictionary;
        return result != null &&
        (
          result.Contains(ERROR_FIELD) ||
          result.ToInt32(ERROR_CODE_FIELD, 0) != 0 ||
          result.GetInt32($"result.{ERROR_CODE_FIELD}") != 0 ||
          result.ToInt32(ERROR_CODE_FIELD.ToLower(), 0) != 0 ||
          result.ToInt32("errcode", 0) != 0
        );
      }
      else if (obj.GetInt32(ERROR_CODE_FIELD) != 0)
      {
        return true;
      }
      return false;
    }
  }
}
